using SPI.AgentServer.Services.Execution;
using System.Text;

namespace SPI.AgentServer.Services.Tools;

/// <summary>
/// 黑名单和特殊人员查询工具
/// 覆盖场景：P-006 黑名单活动
/// </summary>
public class GetBlacklistActivityTool : IQueryTool
{
    private readonly IDatabaseExecutor _executor;
    private readonly ILogger<GetBlacklistActivityTool> _logger;

    public string Name => "get_blacklist_activity";
    public string Description => "查询黑名单人员的活动记录。用于回答'黑名单人员今天有刷卡吗'、'黑名单人员活动情况'等问题。";

    public GetBlacklistActivityTool(
        IDatabaseExecutor executor,
        ILogger<GetBlacklistActivityTool> logger)
    {
        _executor = executor;
        _logger = logger;
    }

    public bool ValidateParameters(Dictionary<string, object> parameters, out List<string> errors)
    {
        errors = new List<string>();
        return true;
    }

    public async Task<ToolResult> ExecuteAsync(Dictionary<string, object> parameters, CancellationToken cancellationToken = default)
    {
        if (parameters == null)
        {
            return new ToolResult
            {
                Success = false,
                Errors = new List<string> { "参数不能为空" }
            };
        }

        try
        {
            string? queryDate = parameters.ContainsKey("queryDate") ? parameters["queryDate"]?.ToString() : null;
            string? personName = parameters.ContainsKey("personName") ? parameters["personName"]?.ToString() : null;

            if (string.IsNullOrEmpty(queryDate))
            {
                queryDate = DateTime.Today.ToString("yyyy-MM-dd");
            }

            var sql = BuildQuery(queryDate, personName);

            _logger.LogInformation("Executing blacklist activity query with SQL: {Sql}", sql);

            var result = await _executor.ExecuteQueryAsync(sql, null, cancellationToken);

            return new ToolResult
            {
                Success = true,
                Data = result.Data,
                Message = "黑名单人员活动查询成功",
                Metadata = new Dictionary<string, object>
                {
                    ["executionTimeMs"] = result.ExecutionTimeMs,
                    ["executedSql"] = sql
                }
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error executing blacklist activity query");
            return new ToolResult
            {
                Success = false,
                Errors = new List<string> { $"查询失败: {ex.Message}" }
            };
        }
    }

    private string BuildQuery(string queryDate, string? personName)
    {
        var sb = new StringBuilder();

        sb.AppendLine("SELECT");
        sb.AppendLine("    g.XM AS name,");
        sb.AppendLine("    g.XGH AS student_id,");
        sb.AppendLine("    bl.Reason AS blacklist_reason,");
        sb.AppendLine("    DATE_FORMAT(g.SJ, '%Y-%m-%d %H:%i:%s') AS access_time,");
        sb.AppendLine("    g.ZJMC AS gate_name,");
        sb.AppendLine("    CASE g.CRBS");
        sb.AppendLine("        WHEN 1 THEN '进'");
        sb.AppendLine("        WHEN 0 THEN '出'");
        sb.AppendLine("        ELSE '未知'");
        sb.AppendLine("    END AS direction");
        sb.AppendLine("FROM TblGateInformation g");
        sb.AppendLine("INNER JOIN TblBlackList bl ON g.XGH = bl.StudentNumber");
        sb.AppendLine($"WHERE DATE(g.SJ) = '{queryDate}'");
        sb.AppendLine("    AND bl.IsValid = 1");

        if (!string.IsNullOrEmpty(personName))
        {
            sb.AppendLine($"    AND g.XM LIKE '%{personName}%'");
        }

        sb.AppendLine("ORDER BY g.SJ DESC");
        sb.AppendLine("LIMIT 100");

        return sb.ToString();
    }
}
